﻿using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;

namespace RxjhServer.bbg
{
	public class AuthServer
	{
		public static ArrayList clients = new ArrayList();

		private string ip;

		private Socket listenSocket;

		private int port;

		public int totalReceive;

		public int totalSend;

		public event MessageeDelegaterE OnSockMessage;

		public AuthServer(string i, int pt)
		{
			this.totalSend = 0;
			this.totalReceive = 0;
			this.ip = i;
			this.port = pt;
			this.Start();
		}

		public void CloseServer()
		{
			this.listenSocket.Close();
		}

		public void Dispose()
		{
			while (AuthServer.clients.Count > 0)
			{
				((SockClienT)AuthServer.clients[0]).Dispose();
			}
			try
			{
				this.listenSocket.Shutdown(SocketShutdown.Both);
			}
			catch
			{
			}
			if (this.listenSocket != null)
			{
				this.listenSocket.Close();
			}
		}

		public virtual void OnAccept(IAsyncResult ar)
		{
			try
			{
				Socket socket = this.listenSocket.EndAccept(ar);
				if (socket != null)
				{
					ClientConnection clientConnection = new ClientConnection(socket, new RemoveClientDelegateE(this.RemoveClient));
					AuthServer.clients.Add(clientConnection);
					clientConnection.OnSockMessage += new MessageeDelegaterE(this.connection1_OnSockMessage);
					clientConnection.Start();
				}
			}
			catch (Exception arg)
			{
				Console.WriteLine("{0}", arg);
			}
			try
			{
				this.listenSocket.BeginAccept(new AsyncCallback(this.OnAccept), this.listenSocket);
			}
			catch
			{
				this.Dispose();
			}
		}

		public void RemoveClient(SockClienT client)
		{
			using (new Lock(AuthServer.clients, "RemoveClient"))
			{
				AuthServer.clients.Remove(client);
			}
		}

		public bool Start()
		{
			try
			{
				this.listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				this.listenSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
				Form1.WriteLine(1, string.Concat(new object[]
				{
					"开始监听百宝端口 ",
					this.port,
					" IP ",
					this.ip.ToString()
				}));
				this.listenSocket.Listen(10);
				this.listenSocket.BeginAccept(new AsyncCallback(this.OnAccept), this.listenSocket);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failled to list on port {0}\n{1}", this.port, ex.Message);
				Form1.WriteLine(1, string.Concat(new object[]
				{
					"监听百宝端口出错 ",
					this.port,
					"   ",
					ex.Message
				}));
				this.listenSocket = null;
				return false;
			}
			return true;
		}

		private void connection1_OnSockMessage(object sender, SockClienT client)
		{
			this.RaiseMessageEvent(sender, client);
		}

		private void RaiseMessageEvent(object Msg, SockClienT client)
		{
			if (this.OnSockMessage != null)
			{
				this.OnSockMessage(Msg, client);
			}
		}
	}
}
